﻿namespace Blaze.Editor.LuaExtensions
{
    using Framework.LuaExtensions;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// 为<see cref="LuaBehaviour"/>选择lua脚本窗口。
    /// </summary>
    [InitializeOnLoad]
    internal class ChooseScriptWindow : AdvancedDropdownWindow
    {
        internal LuaBehaviour m_Target;

        internal static ChooseScriptWindow mInstance;

        protected override bool isSearchFieldDisabled
        {
            get
            {
                var child = m_CurrentlyRenderedTree.GetSelectedChild();
                return child is NewScriptDropdownItem;
            }
        }

        internal string searchString
        {
            get { return m_Search; }
        }

        protected override void OnDisable()
        {
            mInstance = null;
            ProjectEditorPrefs.SetString(mScriptSearchKey, m_Search);
        }

        protected override void OnEnable()
        {
            base.OnEnable();
            m_Search = ProjectEditorPrefs.GetString(mScriptSearchKey, "");
            showHeader = true;
        }

        protected override bool SpecialKeyboardHandling(Event evt)
        {
            var createScriptMenu = m_CurrentlyRenderedTree.GetSelectedChild();
            if (createScriptMenu is NewScriptDropdownItem)
            {
                // When creating new script name we want to dedicate both left/right arrow and backspace
                // to editing the script name so they can't be used for navigating the menus.
                // The only way to get back using the keyboard is pressing Esc.
                if (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter)
                {
                    createScriptMenu.OnAction();
                    evt.Use();
                    GUIUtility.ExitGUI();
                }

                if (evt.keyCode == KeyCode.Escape)
                {
                    GoToParent();
                    evt.Use();
                }

                return true;
            }

            return false;
        }

        internal static bool Show(Rect rect, LuaBehaviour target)
        {
            CloseAllOpenWindows<ChooseScriptWindow>();

            Event.current.Use();
            mInstance = CreateInstance<ChooseScriptWindow>();
            mInstance.m_Target = target;
            mInstance.dataSource = new ChooseScriptDataSource(LuaScriptSourceResolver.Resolve(target));
            mInstance.gui = new ChooseScriptGUI();
            mInstance.Init(rect);
            return true;
        }

        private const string mScriptSearchKey = "ScriptSearchString";
    }
}